<template>
  <view class="box1" :style="'height:' + scanHight + 'px;padding-top:' + statusBarHeight1 + 'px'">
    <!-- #ifdef MP-WEIXIN -->
    <camera
      ref="wxScan"
      class="barcode"
      device-position="back"
      mode="scanCode"
      :flash="isFlash"
      @error="error"
      style="width: 100%; height: 0"
      :style="'height:' + scanHight + 'px'"
      @scancode="scancode"
    ></camera>

    <!-- #endif -->

    <view
      class="tou1 top1"
      :style="'z-index:999; box-sizing: border-box;overflow: visible!important;width: 750rpx;background-color: transparent;x'"
    >
      <image
        @click.stop="fanhui"
        class="image1"
        src="https://pic.bangbangtongcheng.com/static/fanhui_bai.png"
      />
      <!-- #ifndef MP-WEIXIN -->
      <text
        class="tou-operate"
        style="border-radius: 8rpx; display: flex; align-items: center; justify-content: center"
        @click.stop="confirm"
      >
        完成
      </text>
      <!-- #endif -->
      <!-- #ifdef MP-WEIXIN -->
      <text
        v-if="!showPhotoAlbum"
        class="tou-operate"
        style="
          transform: translateY(30px);
          border-radius: 8rpx;
          display: flex;
          align-items: center;
          justify-content: center;
        "
        @click.stop="confirm"
      >
        完成
      </text>
      <!-- #endif -->
    </view>

    <view class="scan-main" :style="'top:' + scanMainTop + 'px'">
      <text class="scan-main-t1">扫二维码</text>
      <text class="scan-main-t2">请您核实二维码正规性后再扫描，谨防欺诈等违规信息</text>
      <view class="scan-main-box" @click="trigger">
        <image
          src="https://pic.bangbangtongcheng.com/static/member/off-light.png"
          mode=""
          class="scan-main-box-img"
        ></image>
        <text class="scan-main-box-t1">{{ isFlash == 'on' ? '关闭手电筒' : '打开手电筒' }}</text>
      </view>
      <view class="tips" v-for="(item, index) in tipsList" :key="index">
        <text class="tips_text">{{ item.tips }}</text>
      </view>
    </view>
    <view class="nums" v-if="userInfo.whetherAdmin == 1 && !showPhotoAlbum">
      <text class="nums_text">扫码数量： {{ scanNum }}</text>
    </view>
  </view>
</template>

<script>
  var setIndex = 0
  export default {
    data() {
      return {
        userInfo: uni.getStorageSync('Pduser'),
        src: '',
        isFlash: 'off',
        scanMainTop: 0,
        scanHight: 0,
        statusBarHeight1: uni.statusBarHeight1 || 20,
        showPhotoAlbum: false,
        tipsList: [],
        scanNum: 0,
        longitude: '',
        latitude: '',
        type: '',
        qrCodeList: [],
      }
    },
    onLoad(e) {
      this.from = e.from
      if (e.from == 'scanCode') {
        this.showPhotoAlbum = false
      } else {
        this.showPhotoAlbum = true
      }
      this.type = e.type

      let that = this
      uni.getSystemInfo({
        success: function (res) {
          that.scanHight = res.screenHeight
          that.scanMainTop = res.screenHeight / 2 + uni.upx2px(300)
        },
      })
      if (uni.getStorageSync('locationState') == 1) {
        this.getLocation()
      }
    },
    methods: {
      async getLocation() {
        this.getLocation1()
      },
      getLocation1() {
        let _this = this
        console.log('getLocation1')
        uni.getLocation({
          type: 'gcj02',

          // highAccuracyExpireTime: "3000",
          success(res) {
            _this.latitude = res.latitude
            _this.longitude = res.longitude
          },
          fail:(res) => {
            console.log(res, '经纬度没有授权');
            this.$SHOWMODAL_TO_SETTINGS();
            uni.setStorageSync('locationState', 0)
            uni.hideLoading()
            if (uni.getStorageSync('locationState') == 0) {
              // uni.showModal({
              //   title: '提示',
              //   content: '您已关闭位置权限或获取位置信息失败',
              //   success: function (res) {
              //     if (res.confirm) {
              //       // plus.runtime.openURL("app-settings:");
              //       if (that.userInfo.merchantId && !that.longitude) {
              //         that.fanhui()
              //         return
              //       }
              //     } else if (res.cancel) {
              //       console.log('用户点击取消')
              //       if (that.userInfo.merchantId && !that.longitude) {
              //         that.fanhui()
              //         return
              //       }
              //     }
              //   },
              // })
              return false
            }
          },
        })
      },
      trigger() {
        this.isFlash = this.isFlash == 'off' ? 'on' : 'off'
      },
      scancode(e) {
        let result = e.target.result
        this.debounceThrottleMix(result)
        // console.log(2, e.target.result)
        // if(!this.timer){

        // 	this.timer = setTimeout(()=>{
        // 		this.timer = null

        // 		uni.showToast({
        // 			title:'成功',
        // 			icon:'none'
        // 		})
        // 		this.scanSuccess(e)

        // 	},5000)
        // }
      },
      checkQRcode(res) {
        var res2 = {}
        var reg = /([^?=&]+)=([^&]*)/g
        var tempArr = []
        while ((tempArr = reg.exec(res))) {
          res2[tempArr[1]] = tempArr[2]
        }
        return res2
      },
      debounceThrottleMix(result) {
        const res2 = this.checkQRcode(result)
        if (res2.pkgname == 'com.cn.conven') {
          if (this.from == 'scanCode') {
            if (this.timer) {
              return false
            }
            this.ifPush({
              result: result,
              res2,
            })
            // uni.showToast({
            // 	title: '扫码成功',
            // 	icon: "none",
            // 	duration:1000
            // })

            this.timer = setTimeout(() => {
              this.timer = null
            }, 1500)
          } else {
            if (!this.timer) {
              // uni.showToast({
              // 	title: '扫码成功',
              // 	icon: "none"
              // })
              this.scanDeal({
                result: result,
              })
              this.timer = setTimeout(() => {
                this.timer = null
              }, 1000)
            }
          }
        }
      },
      scanDeal(ress) {
        let that = this
        if (ress.result.split('?')[0] != 'https:\/\/a.app.qq.com/o/simple.jsp') {
          // uni.showToast({
          // 	title: "请扫描正确的二维码",
          // 	icon: "none",
          // 	mask: true
          // });
          that.showTips('请扫描正确的二维码')
          return
        }
        console.log(ress, 'ress-----')
        if (ress.result.includes('codeId')) {
          if (that.userInfo.merchantId && !that.longitude) {
            that.fanhui()
            return
          }
          let codeId = ''
          let merchantId = ''
          codeId = ress.result.split('&')[1].split('=')[1]
          merchantId = ress.result.split('&')[2].split('=')[1]
          console.log(codeId, 'codeId1111111----')
          console.log(merchantId, 'merchantId1111111----')
          this.$myRequest
            .get('/api/mobile/vehicleOwner/getLicensePlateNumberByCodeId', {
              codeId: codeId,
              longitude: that.longitude,
              latitude: that.latitude,
              merchantId: that.userInfo.merchantId,
            })
            .then(async (res) => {
              if (that.userInfo.merchantId) {
                if (res.codeBindRecord.distance > 0.2) {
                  uni.$emit('commonScanResult3')
                  that.fanhui()
                  return
                }
                var status = 1
                await this.$myRequest
                  .get('/api/mobile/vehicleOwner/getMerchantById', {
                    merchantId: this.userInfo.merchantId,
                  })
                  .then((res) => {
                    status = res.merchantInfo.status
                  })
                if (status != 1) {
                  that.showTips('商家已被冻结，不可发放礼品')
                  return
                } else {
                }
                console.log(merchantId, '商家扫描走完了-----')
                that.fanhui()
                uni.$emit('commonScanResult2', ress)
              } else if (that.userInfo.whetherAdmin == 1) {
                if (res.codeBindRecord.isMerchant == '1') {
                  that.showTips(`该二维码已作废`)
                  return false
                }
                if (res.whetherExistence == 1) {
                  that.showTips('该码已绑定:' + res.codeBindRecord.licensePlateNumber)
                  return false
                }
                if (res.emptyOrNotQrCode) {
                  that.showTips('该二维码未分配商家')
                  return false
                } else {
                  that.showTips('该码已分配' + `"${res.codeBindRecord.merchantName}"`)
                  return false
                }
              } else {
                if (res.emptyOrNotQrCode) {
                  that.showTips('该二维码未分配商家')
                  return false
                }
                if (res.codeBindRecord.isMerchant == '1') {
                  // that.showTips(`该二维码已作废`)
                  // return false
                  uni.redirectTo({
                    url: '/pages_my/bangClub?index=1',
                  })
                }
                if (res.codeBindRecord && res.codeBindRecord.userId == that.userInfo.id) {
                  uni.redirectTo({
                    url: '/pages_my/bangClub?index=1',
                  })
                } else if (res.whetherExistence == 1) {
                  uni.redirectTo({
                    url: '/pages_my/bangClub?index=1',
                  })
                  // that.showTips('该码已绑定:' + res.codeBindRecord.licensePlateNumber)
                } else {
                  uni.redirectTo({
                    url:
                      '/pages_owner/carMember/bindQRCode?codeId=' +
                      codeId +
                      '&merchantId=' +
                      merchantId,
                  })
                }
              }
            })
        } else {
          that.fanhui()
          uni.$emit('commonScanResult2', ress)
        }
      },
      ifPush(ress) {
        let that = this
        if (ress.result.split('?')[0] != 'https:\/\/a.app.qq.com/o/simple.jsp') {
          // uni.showToast({
          // 	title: "请扫描正确的二维码",
          // 	icon: "none",
          // 	mask: true
          // });
          that.showTips('请扫描正确的二维码')
          return
        }
        console.log(ress, 'ress-----')
        if (ress.result.includes('codeId')) {
          let codeId = ''
          let merchantId = ''
          codeId = ress.result.split('&')[1].split('=')[1]
          merchantId = ress.result.split('&')[2].split('=')[1]
          console.log(codeId, 'codeId1111111----')
          console.log(merchantId, 'merchantId1111111----')
          this.$myRequest
            .get('/api/mobile/vehicleOwner/getLicensePlateNumberByCodeId', {
              codeId: codeId,
              longitude: that.longitude,
              latitude: that.latitude,
              merchantId: that.userInfo.merchantId,
            })
            .then(async (res) => {
              if (that.userInfo.whetherAdmin == 1) {
                if (this.type == 4) {
                  //送货
                  if (res.whetherExistence == 1) {
                    that.showTips('该码已绑定:' + res.codeBindRecord.licensePlateNumber)
                    return false
                  }
                  if (res.emptyOrNotQrCode) {
                    // that.showTips('该二维码未分配商家')
                    for (var i = 0; i < that.qrCodeList.length; i++) {
                      console.log(ress.res2.codeId, that.qrCodeList[i].codeId)
                      if (ress.res2.codeId == that.qrCodeList[i].codeId) {
                        that.showTips('该码已存在')
                        return false
                      }
                    }
                    that.qrCodeList.push(ress.res2)
                    that.scanNum++
                    that.showTips('扫码成功')
                    return false
                  } else {
                    that.showTips('该码已分配' + `"${res.codeBindRecord.merchantName}"`)
                    return false
                  }
                } else {
                  //取货
                  if (res.whetherExistence == 1) {
                    that.showTips('该码已绑定:' + res.codeBindRecord.licensePlateNumber)
                    return false
                  }
                  if (res.emptyOrNotQrCode) {
                    that.showTips('该二维码未分配商家')
                    return false
                  } else {
                    if (res.codeBindRecord.merchantId == this.merchantId) {
                      //二维码分配的商家与当前商家一致
                      for (var i = 0; i < that.qrCodeList.length; i++) {
                        console.log(ress.res2.codeId, that.qrCodeList[i].codeId)
                        if (ress.res2.codeId == that.qrCodeList[i].codeId) {
                          that.showTips('该码已存在')
                          return false
                        }
                      }
                      that.qrCodeList.push(ress.res2)
                      that.scanNum++
                      that.showTips('扫码成功')
                      return false
                    } else {
                      that.showTips('该码已分配' + `"${res.codeBindRecord.merchantName}"`)
                      return false
                    }
                  }
                }
              }
            })
        } else {
          that.fanhui()
          uni.$emit('commonScanResult2', ress)
        }
      },
      showTips(tips) {
        let that = this
        setIndex++
        this.tipsList.push({
          tips,
          index: setIndex,
        })
        setTimeout(() => {
          that.delTips(tips, setIndex)
        }, 3000)
      },
      delTips(tips, index) {
        let delIndex = 0
        let arr = this.tipsList.forEach((el, index) => {
          if (el.tips == tips && el.index == index) {
            delIndex = index
          }
        })
        this.tipsList.splice(delIndex, 1)
      },
      scanSuccess() {},
      fanhui() {
        uni.navigateBack({
          delta: 1,
        })
      },
      confirm() {
        setTimeout(() => {
          uni.$emit('commonScanResult', JSON.parse(JSON.stringify(this.qrCodeList)))
          this.fanhui()
        })
      },

      takePhoto() {
        const ctx = uni.createCameraContext()
        ctx.takePhoto({
          quality: 'high',
          success: (res) => {
            this.src = res.tempImagePath
          },
        })
      },
      error(e) {
        console.log(e.detail)
      },
    },
  }
</script>

<style lang="scss">
  page {
    position: relative;
  }

  .barcode {
    position: absolute;
    top: 0%;
    left: 0%;
    width: 750rpx;
    background-color: #808080;
  }

  .btn {
    top: 20rpx;
    width: 730rpx;
    margin-left: 10rpx;
    margin-top: 10rpx;
    background-color: #458b00;
    border-radius: 10rpx;
  }

  .box1 {
    width: 750rpx;
    position: relative;
    background-color: #458b00;
  }
  .scan-main {
    z-index: 9999;
    position: absolute;
    top: 700rpx;
    left: 0%;
    width: 750rpx;
    height: 240rpx;
    // background-color: #458B00;
    align-items: center;
    display: flex;
    flex-direction: column;
  }
  .scan-main-t1 {
    font-size: 30rpx;
    font-weight: 400;
    color: #ffffff;
    line-height: 28rpx;
    margin-bottom: 34rpx;
    text-align: center;
  }
  .scan-main-t2 {
    font-size: 24rpx;
    font-weight: 400;
    color: #ffffff;
    line-height: 28rpx;
    margin-bottom: 34rpx;
  }
  .scan-main-box {
    width: 252rpx;
    height: 68rpx;
    background: rgba(0, 0, 0, 0.7);
    border-radius: 8rpx 8rpx 8rpx 8rpx;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
  }
  .scan-main-box-img {
    width: 48rpx;
    height: 48rpx;
    margin-right: 8rpx;
  }
  .tips {
    padding: 10rpx 20rpx;
    background: rgba(0, 0, 0, 0.7);
    border-radius: 8rpx;

    line-height: 1.5;
    max-width: 500rpx;
    text-align: center;
    margin: 50rpx auto 0;
  }
  .tips_text {
    color: #ffffff;
    font-size: 30rpx;
  }
  .scan-main-box-t1 {
    font-size: 30rpx;
    font-weight: 400;
    color: #ffffff;
    line-height: 68rpx;
  }

  .tou1 {
    position: relative;

    width: 750rpx !important;
    height: 128rpx !important;
    text-align: center;
    line-height: 88rpx;
    font-size: 36rpx;
    color: #fff;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    padding: 0 30rpx;
    overflow: visible !important;
  }
  .tou-operate {
    width: 128rpx;
    height: 64rpx;
    line-height: 64rpx;
    background: #64b6a8;

    font-size: 30rpx;
    font-weight: 400;
    color: #ffffff;
    text-align: center;
  }
  .image1 {
    position: relative;
    width: 32rpx;
    height: 32rpx;
    // top: 116rpx;
    left: 0rpx;
  }

  .image2 {
    position: absolute;
    width: 56rpx;
    height: 56rpx;
    // top: 104rpx;
    right: 30rpx;
  }

  p {
    position: absolute;
    // top: 90rpx;
    line-height: 45rpx;
    bottom: 21rpx;
    right: 30rpx;
    font-size: 32rpx;
    color: #fff;
  }
</style>
